package main

import (
	"net/http"

	"github.com/julienschmidt/httprouter"
)

// 中间件
type middlerWareHandler struct {
	r *httprouter.Router
	l *ConnLimiter // 流控制
}

// NewMiddlerWareHandler 构造函数
func NewMiddlerWareHandler(r *httprouter.Router, cc int) http.Handler {
	m := middlerWareHandler{}
	m.r = r
	m.l = NewConnLimiter(cc)
	return m
}
func (m middlerWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if !m.l.GetConn() {
		sendErrorResponse(w, http.StatusTooManyRequests, "Too many request")
		return
	}
	m.r.ServeHTTP(w, r)
	defer m.l.ReleaseConn()
}

// RegisterHandler 注册路由
func RegisterHandler() *httprouter.Router {
	router := httprouter.New()
	router.GET("/videos/:vid-id", streamHandler)
	router.POST("/upload/:vid-id", uploadHandler)
	// 测试上传使用页面
	router.GET("/testpage", testPageHandler)

	return router
}

func main() {
	r := RegisterHandler()
	mh := NewMiddlerWareHandler(r, 2) // 测试设置2
	http.ListenAndServe(":9000", mh)
}
